﻿using MvcApplication.Common;
using MvcApplication.CommonWebApi.Domain;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data.Common;
using System.Web;

namespace MvcApplication.CommonWebApi
{
    public class CommonWebApiService
    {
        public string LoadCommonAPi(string commonId)
        {
            var scriptCollection = new ScriptCollection();
            var script = scriptCollection.Get(commonId);
            if (script == null) throw new BizException("接口不存在");

            var paramArray = PrepareParameters(script).ToArray();
            if (script.UseDataSet)
            {
                var dataSet = MySqlADO.GetDataSet(script.ConnInfo.ConnString, script.Text, paramArray);

                string result = string.Empty;
                if (dataSet.Tables.Count == 1)
                {
                    result = JsonConvert.SerializeObject(dataSet.Tables[0]);
                }
                else
                {
                    result = JsonConvert.SerializeObject(dataSet);
                }

                return result;
            }
            else
            {
                using (var reader = MySqlADO.GetDataReader(script.ConnInfo.ConnString, script.Text, paramArray))
                {
                    var temporary = new List<Dictionary<string, object>>();
                    var cols = new List<string>();
                    for (var i = 0; i < reader.FieldCount; i++)
                    {
                        cols.Add(reader.GetName(i));
                    }

                    while (reader.Read())
                    {
                        temporary.Add(SerializeRow(cols, reader));
                    }

                    var result = JsonConvert.SerializeObject(temporary);
                    return result;
                }
            }
        }

        static List<MySqlParameter> PrepareParameters(Script script)
        {
            var parameter = new List<MySqlParameter>();

            foreach (var param in script.Params)
            {
                var p = new MySqlParameter(param.Name, param.MySqlDbType);
                var queryString = HttpContext.Current.Request.QueryString;
                p.Value = queryString[param.Name];

                parameter.Add(p);
            }
            return parameter;
        }

        private Dictionary<string, object> SerializeRow(IEnumerable<string> cols, DbDataReader reader)
        {
            var result = new Dictionary<string, object>();
            foreach (var col in cols)
            {
                result.Add(col, reader[col]);
            }
            return result;
        }
    }
}
